#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2025/8/23
# @File           : tortoise_logger.py
# @IDE            : PyCharm
# @Desc           : Tortoise ORM 日志统一处理器

import logging
from typing import Dict, Any

from loguru import logger as loguru_logger

from .log_handlers import InterceptHandler


def setup_tortoise_logger(level: str = "DEBUG") -> Dict[str, Any]:
    """
    配置 Tortoise ORM 日志，将其转发到 Loguru

    Args:
        level: 日志级别，默认为 "DEBUG"

    Returns:
        Dict[str, Any]: Tortoise 日志配置字典
    """
    # 移除已存在的处理器
    for logger_name in ["tortoise", "tortoise.db_client"]:
        logger = logging.getLogger(logger_name)
        for handler in logger.handlers[:]:
            logger.removeHandler(handler)
        logger.addHandler(InterceptHandler())
        logger.setLevel(level)
        logger.propagate = False

    # 返回 Tortoise 配置
    return {
        "version": 1,
        "disable_existing_loggers": False,
        "handlers": {"intercept": {"class": "applications.log.log_handlers.InterceptHandler"}},
        "loggers": {
            "tortoise": {"handlers": ["intercept"], "level": level},
            "tortoise.db_client": {"handlers": ["intercept"], "level": level},
        },
    }


# 创建 tortoise 日志配置
logger_tortoise = setup_tortoise_logger()


__all__ = ["logger_tortoise", "setup_tortoise_logger"]
